%% 1.1.1
A = [1,2,4;2,2,1;3,2,0]
y = [5;4;2]
tic
x_1 = inv(A)*y
toc
tic
x_2 = mldivide(A,y)
toc
norm(A*x_1-y)
norm(A*x_2-y)
%% 1.1.2
A = 10;
n = 1:100;

x = (0:10)
f = zeros(size(x))

hold on
for i = x  
 f = A*sum((4./(pi*2*n).*sin((2*n-1)*i)))
 plot(i,f, '*')
 pause(1)
end 
hold off
%% 1.1.2 alternativ
A = 10;
n = 1:100;
x = 0:10;

hold on
for x_c = x
    f = 0;
    for i = n
        f = f + A*sum((4/(pi*2*i)*sin((2*i-1)*x_c)));
    end
    
    plot(x(x_c+1), f, '*')
end 
hold off

%% 1.1.3

t_konsts = 0:10;
[x,y] = meshgrid(0:1:10)
z_0 = sin((x*pi)/10).*sin((y*pi)/10)

for i = t_konsts
    hold on;
    z = z_0.*abs(sin(i));
    surf(x, y, z);
    pause(3);
end
hold off;
%% 1.2.1
clear all
close all
T0 = 0.05;
t(1) = 0;
m = 1;
c = 1;
k = 2;
T = 1:5;



for i = 1:5
    T(i) = T0*i;
end


for i = 1:5
    Ta = T(i);
    t = 0:Ta:20;
    x = zeros(2, size(t, 2));
    for n = 1:size(t,2)-1
        x(:,n+1) = x(:,n) + Ta*([0  1; -k/m -c/m]*[x(1,n);x(2,n)] + [0;1/m]);

    end
    hold on
    subplot(2,1,1)
    plot(t,x(1,:))
    hold on
    subplot(2,1,2)
    plot(t,x(2,:))
end
legend(num2str(T'))

l1 = (-c+sqrt(c^2-4*m*k))/(2*m);
l2 = (-c-sqrt(c^2-4*m*k))/(2*m);
t = 0:T0:20;
x = zeros(2, size(t, 2));
x(1, :) = (l2*(-1 + exp(l1*t)) - l1*(-1 + exp(l2*t)))/(l1*l2*(-l2 + l1));
x(2, :) = 1/(l1-l2) * (exp(l1*t)-exp(l2*t));
hold on
subplot(2,1,1)
plot(t,x(1, :))
hold on
subplot(2,1,2)
plot(t,x(2, :))

%% 3.
m = 1; % kg
c = 1; % Ns/m
k = 2; % N/m
Ta = .1; % s


% state space representation
A = [0 1; -k/m -c/m];
B = [0;1/m];
C = [1,0];
D = 0;

% construct system
sys = ss(A,B,C,D);

% discretize system
discrete_sys = c2d(sys,Ta,'zoh');

% plot step response
subplot(2,1,1)
step(discrete_sys)









